Skip to content

fix: preserve integer precision in modular exponentiation - #2035

Open
lanqing431 wants to merge 1 commit into
TheAlgorithms:masterfrom
lanqing431:fix/exact-modular-multiplication
Open

lanqing431 wants to merge 1 commit into
TheAlgorithms:masterfrom
lanqing431:fix/exact-modular-multiplication

Conversation

@lanqing431

@lanqing431 lanqing431 commented Nov 23, 2026 •

Copy link
Copy Markdown

Describe your change:

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Documentation change?

modularBinaryExponentiation(2147483646, 2, 2147483647) returns 2147483644 instead of 1. Inputs and the final remainder fit within safe integers, but intermediate multiplication exceeds Number's exact integer range. With (123456789, 12345, 1000000007), the result is 933234527 instead of 614455772.

Use BigInt for the intermediate modular multiplications and keep the existing Number return type and recursive structure. Also reduce the exponent-zero identity modulo m, so modulus 1 returns 0. The supported Node.js versions already provide BigInt; no dependency is added.

Four new regression cases use exact expected values checked independently with Python's integer pow(a, n, m). Existing small-number behavior and the public export remain unchanged.

Validation (Node.js 24.22.0): all four new cases fail on unchanged master. npm test -- --maxWorkers=2 --minWorkers=1 passes all 11968 tests in 345 files. npm run check-style and git diff --check pass.

Additionally, npm test -- Maths/test/PascalTriangle.test.js --maxWorkers=2 --minWorkers=1 passes all 6 tests in that file.

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is my own contribution and does not copy another proposed fix.
  • This PR only changes one algorithm file and its tests.
  • All files remain in their existing directories.

Prepared with OpenAI Codex assistance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant